package TcpServerAndClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        // 使用线程池来创建线程  能起到线程的复用
        ExecutorService poll = Executors.newCachedThreadPool();
        while (true) {
            // 先建立连接
            Socket clientSocket = serverSocket.accept();
//            //引入多线程 一个线程负责一个客户端，否则无法运行多客户端  会有阻塞

//            Thread t = new Thread(() -> {
//                // 处理一个连接
//                try {
//                    processConnection(clientSocket);
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            });
//            t.start();
            poll.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        //1 打印日志  告诉当前客户端连接上了
        System.out.printf("[%s:%d] 客户端上线！\n", clientSocket.getInetAddress(), clientSocket.getPort());
        //2 从socket中 获取到流对象  来进一步进行操作
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            //3 也需要一个循环来重复进行一个客户端发来的多个请求
            Scanner scanner = new Scanner(inputStream);
            while (true) {
                //3.1 读取请求并解析
                if (!scanner.hasNext()) {
                    System.out.printf("[%s:%d] 客户端下线!\n", clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }
                String request = scanner.next();
                //3.2 处理请求
                String response = process(request);
                //3.3 写回客户端
                outputStream.write(response.getBytes());
                // 服务器打印日志
                System.out.printf("[%s:%d] req=%s resp=%s", clientSocket.getInetAddress(), clientSocket.getPort(),
                        request, response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 注意关闭clientSocket
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request + '\n';
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }

}
